<script setup>
import { useUserInfoStore } from "@/stores/userInfo";
import { ref } from "vue";
// 省市区选择器
import { pcaTextArr } from "element-china-area-data";
import { ElMessage, ElMessageBox } from "element-plus";
import {
    addAddressService,
    getAddressListService,
    deleteAddressService,
    updateAddressService,
} from "@/api/address";

const userInfoStore = useUserInfoStore();

// 新增弹出框状态
const addressDialogVisible = ref(false);

// 地址数据模型
const address = ref({
    addressName: "",
    addressPhone: "",
    addressArea: "",
    description: "",
    addressDescription: "",
});

// from表单验证规则
const addressForm = ref();
// 表单验证规则
const rules = {
    addressName: [
        { required: true, message: "请填写收货人姓名", trigger: "blur" },
        {
            pattern: /^[\u4e00-\u9fa5a-zA-Z]{2,10}$/,
            min: 2,
            max: 10,
            message: "收货人姓名长度在 2 到 10 个字符，仅包含英文和汉字",
            trigger: "blur",
        },
    ],
    addressPhone: [
        { required: true, message: "请填写收货人手机号", trigger: "blur" },
        {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号格式不正确",
            trigger: "blur",
        },
    ],
    addressArea: [
        { required: true, message: "请选择省市区", trigger: "change" },
    ],
    description: [
        { required: true, message: "请输入正确的地址", trigger: "blur" },
    ],
};

// 提交函数
const submitAddress = async (chooise) => {
    addressForm.value.validate(async (valid) => {
        if (valid) {
            // 将省市区和详细地址拼接成完整地址
            address.value.addressDescription =
                address.value.addressArea.join("") + address.value.description;
            // 结果集
            let result = {};
            switch (chooise) {
                case "修改":
                    // 调用修改地址接口
                    result = await updateAddressService(address.value);
                    ElMessage.success(
                        result.message ? result.message : "修改地址成功"
                    );
                    break;
                case "新增":
                    // 调用新增地址接口
                    result = await addAddressService(address.value);
                    ElMessage.success(
                        result.message ? result.message : "新增地址成功"
                    );
                    break;
            }

            // 重新获取地址信息
            result = await getAddressListService();
            userInfoStore.address = result.data;
            // 关闭弹出框
            addressDialogVisible.value = false;
            // 清空表单
            addressForm.value.resetFields();
            // 重置地址数据模型
            address.value = {
                addressName: "",
                addressPhone: "",
                addressArea: "",
                description: "",
                addressDescription: "",
            };
        } else {
            ElMessage.error("请检查输入项");
        }
    });
};

// 删除地址
const deleteAddress = async (data) => {
    ElMessageBox.alert(
        data.addressName +
            "  " +
            data.addressPhone +
            "  " +
            data.addressDescription,
        "警告",
        {
            confirmButtonText: "确认删除",
            closeOnClickModal: true,
        }
    ).then(() => {
        deleteAddressService(data.addressId).then((result) => {
            ElMessage.success(result.message ? result.message : "删除地址成功");
            // 重新获取地址信息
            getAddressListService().then((result) => {
                userInfoStore.address = result.data;
            });
        });
    });
};

const openAddressDialog = (data) => {
    if (data) {
        address.value = data;
    } else {
        // 清空address数据模型
        address.value = {
            addressName: "",
            addressPhone: "",
            addressArea: "",
            description: "",
            addressDescription: "",
        };
    }
    addressDialogVisible.value = true;
};
</script>

<template>
    <el-container>
        <el-main>
            <el-card class="page-container">
                <template #header>
                    <div class="header">
                        <span style="font-size: 20px">收货地址</span>
                        <el-button
                            style="float: right"
                            type="primary"
                            @click="openAddressDialog()"
                            >新增地址</el-button
                        >
                    </div>
                </template>
                <el-table :data="userInfoStore.address" max-height="450">
                    <el-table-column
                        width="150"
                        label="收货人"
                        prop="addressName"
                    />
                    <el-table-column
                        width="180"
                        label="手机号"
                        prop="addressPhone"
                    />
                    <el-table-column label="地址" prop="addressDescription" />
                    <el-table-column width="180" label="操作">
                        <template #default="scope">
                            <el-button
                                type="primary"
                                @click="openAddressDialog(scope.row)"
                                >编辑</el-button
                            >
                            <el-button @click="deleteAddress(scope.row)"
                                >删除</el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </el-main>
    </el-container>

    <!-- 地址弹出框 -->
    <el-dialog
        class="address-dialog"
        v-model="addressDialogVisible"
        align-center
    >
        <template #header>
            <span v-if="address.addressId" style="font-size: 20px"
                >修改地址</span
            >
            <span v-else style="font-size: 20px">新增地址</span>
        </template>
        <el-form
            ref="addressForm"
            :model="address"
            label-width="100px"
            :rules="rules"
        >
            <el-form-item label="收货人：" prop="addressName">
                <el-input v-model="address.addressName"></el-input>
            </el-form-item>
            <el-form-item label="手机号：" prop="addressPhone">
                <el-input v-model="address.addressPhone"></el-input>
            </el-form-item>
            <el-form-item label="省市区：" prop="addressArea">
                <el-cascader
                    size="large"
                    :options="pcaTextArr"
                    v-model="address.addressArea"
                >
                </el-cascader>
            </el-form-item>
            <el-form-item label="详细地址：" prop="description">
                <el-input v-model="address.description"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button
                style="float: left"
                @click="addressDialogVisible = false"
            >
                取消</el-button
            >
            <el-button
                v-if="address.addressId"
                type="primary"
                @click="submitAddress('修改')"
            >
                修改</el-button
            >
            <el-button v-else type="primary" @click="submitAddress('新增')">
                提交</el-button
            >
        </template>
    </el-dialog>
</template>

<style scoped lang = "scss">
@import "@/assets/style/config.scss";
.page-container {
    border-radius: $borderRadius;
    width: 85%;
}

.address-dialog {
    max-height: 500px;
    max-width: 1000px;
    overflow-y: auto;
    overflow-x: hidden;
    border-radius: $borderRadius;
}
</style>
